import { baseApiUrl, path } from "../../utils/config";
import { orderInfo, orderPayment } from '../../utils/api';
import paymentRequest from '../../utils/api';
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
Page({
  data: {
    baseImageUrl: baseApiUrl,

    name: "",
    phone: "",
    address: "",
    address_id: null,

    id: null,
    shopping_name: "",
    synopsis: "",
    price: 0,
    freight: "",
    rato: 1,

    count: 1,
    total: 0.00,
    total_integral: 0.00,
    type: 1
  },
  async onLoad(options) {
    let { id } = options;
    let res = await orderInfo({ id });
    let count = res.order.number;
    let product = res.order.product;
    let { thumbnail, synopsis, price, freight } = product;
    let shopping_name = product.name;

    let rato = res.integral_rato;
    this.setData({ id, cover: thumbnail, shopping_name, synopsis, price, count, freight, rato });
    this.diff_price();

    let address = res.order.address;
    if (!address) return false;
    let { name, phone, province, city, area } = address;
    let address_id = address.id;
    address = address.address;
    address = `${province}${city}${area}${address}`;
    this.setData({ name, phone, address, address_id });
  },
  onShow() {
    let address = app.globalData.address;
    if (!address) return false;
    let { name, phone, province, city, area, id } = address;
    address = address.address;
    address = `${province}${city}${area}${address}`;
    this.setData({ name, phone, address, address_id: id });
    this.diff_price();
  },
  diff_price() {
    let { price, count, rato } = this.data;
    let total = (Number(price) * Number(count)).toFixed(4);
    let total_integral = (total / rato).toFixed(0);
    this.setData({ total, total_integral });
  },
  // baseChange(e) {
  //   let count = e.detail;
  //   let price = this.data.price;
  //   let total = (Number(price) * Number(count)).toFixed(4);
  //   this.setData({ count, total });
  //   this.diff_price();
  // },
  changePayType(e) {
    let { type } = e.currentTarget.dataset;
    this.setData({ type });
    this.diff_price();
  },
  router(e) {
    let { url } = e.currentTarget.dataset;
    wx.navigateTo({ url });
  },
  async submit() {
    let address_id = this.data.address_id;
    if (!address_id) {
      Toast('请选择收货地址');
      return false;
    };
    let product_id = this.data.id;
    let pay_mode = this.data.type;
    let { pay_data } = await orderPayment({ id: product_id, address_id, pay_mode });
    await paymentRequest(pay_data);
    Toast.success('购买成功');
    setTimeout(() => {
      wx.navigateTo({ url: '/pages/order_list/order_list' });
    }, 1500);
  },
  onShareAppMessage() {
    let poster = app.globalData.poster;
    return {
      path,
      imageUrl: poster
    }
  },
  onShareTimeline() { }
})